package com.alpha.runes.core;

import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Rect;
import android.text.TextUtils;
import android.widget.ImageView;

import com.alpha.runes.Common;
import com.alpha.runes.util.AESUtil;
import com.alpha.runes.util.LogUtils;
import com.alpha.runes.util.OKGoUtil;
import com.alpha.runes.util.SharedPreferenceUtils;
import com.alpha.runes.util.Tool;
import com.alpha.runes.util.ViewUtil;
import com.alpha.runes.view.RunesGuideDialog;
import com.alpha.runes.view.ViewManager;
import com.alpha.runes.R;
import com.alpha.runes.view.RunesDialog;
import com.alpha.runes.view.RunesFloatBall;
import com.alpha.runes.view.MagnetViewListener;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;

import java.util.Base64;
import java.util.HashMap;

public class RunesManager {

    public Activity mContent;
    public int recommendRate = 10;
    public Boolean isInitRunes = false;
    public Boolean isInitRunesManager = false;
    private static RunesManager runesManager;

    private SharedPreferences preferences;

    private String token = "";

    // 是否是加速状态
    boolean isSpeeding = false;

    // 是否显示悬浮球
    boolean isShowSpeedBall = true;

    // 是否显示引导dialog
    boolean isShowGuideDialog = true;


    private float rateFloat = 10f;

    private RunesManager() {
    }

    public static RunesManager getInstance() {
        if (runesManager == null) {
            synchronized (RunesManager.class) {
                runesManager = new RunesManager();
            }
        }
        return runesManager;
    }

    public interface InitRunesManagerCallback {
        void onSuccess();

        void onFailed(RunesStatusCode runesStatusCode);
    }

    public interface RunesStatusCallback {
        void onSuccess();

        void onFailed(RunesStatusCode runesStatusCode);
    }

    public static class TriggerRunesException extends Exception {
        private final int code;

        public TriggerRunesException(int code) {
            this.code = code;
        }

        public int getCode() {
            return code;
        }
    }

    // config包含渠道号、游戏的uuid标识、是否启用悬浮球、默认推荐倍数
    public void init(HashMap<String, String> config, Activity context, InitRunesManagerCallback initRunesManagerCallback) {
        // 1.根据本地加速配置文件是否存在，判断要不要发起请求，如果没有加速配置文件，需要请求接口获取加速配置文件，存入本地设备；
        // 2.通过config中的字段判断是否显示悬浮球；
        // 3.完成RunesManager初始化通过InitRunesManagerCallback回调给渠道方SDK；
        // 4.如果初始化成功了将isInitRunesManager改为true；
        preferences = context.getPreferences(Context.MODE_PRIVATE);
        this.mContent = context;

        String configData = (String) SharedPreferenceUtils.getData(preferences, Common.SPEED_CONFIG_FILE, "");

        String appKey = config.get(Common.ALPHA_SPEED_APPKEY); // 平台创建游戏对应的appKey
        String channelCode = config.get(Common.ALPHA_SPEED_CHANNELCODE); // 渠道号（注册平台即可获得）
        String floatBall = config.get(Common.ALPHA_SPEED_FLOATBALL); // 是否使用悬浮球（0关闭、1展示，助手会在游戏界面放置一个悬浮球供用户操作）
        String rate = config.get(Common.ALPHA_SPEED_RATE); // 默认建议加速的倍数

        if (!TextUtils.isEmpty(rate)) {
            rateFloat = Float.parseFloat(rate);
        }

        // 初始化，网络请求
        if (TextUtils.isEmpty(configData)) {

            initHttp(context, appKey, channelCode, floatBall, initRunesManagerCallback);

        } else {
            isInitRunesManager = true;
            DataBean dataBean = new Gson().fromJson(configData, DataBean.class);
            token = dataBean.getToken();

            // 默認是1，需要顯示加速球
            if (!"0".equals(floatBall)) {
                showFloatBallView(context, initRunesManagerCallback);
            }
        }
    }

    /**
     * 网络请求
     *
     * @param context
     * @param appKey
     * @param channelCode
     * @param floatBall
     * @param initRunesManagerCallback
     */
    private void initHttp(Activity context, String appKey, String channelCode, String floatBall, InitRunesManagerCallback initRunesManagerCallback) {
        OkGo.getInstance().init(context.getApplication());
        OKGoUtil.getInstance().postRequest(appKey, channelCode, new StringCallback() {
            @Override
            public void onSuccess(Response<String> response) {
                EntityBean entityBean = new Gson().fromJson(response.body(), EntityBean.class);
                if (!TextUtils.isEmpty(entityBean.getData())) {
                    String text = AESUtil.decrypt(entityBean.getData());
                    if (!TextUtils.isEmpty(text)) {
                        isInitRunesManager = true;
                        // 存儲配置文件
                        SharedPreferenceUtils.putData(preferences, Common.SPEED_CONFIG_FILE, text);

                        DataBean dataBean = new Gson().fromJson(text, DataBean.class);
                        token = dataBean.getToken();

                        // 默認是1，需要顯示加速球
                        if (!"0".equals(floatBall)) {
                            showFloatBallView(context, initRunesManagerCallback);
                        }

                        initRunesManagerCallback.onSuccess();
                        LogUtils.debug("DataBean  token " + dataBean.getToken() + "===============+DataBean  rate=" + dataBean.getRatio());
                    } else {
                        initRunesManagerCallback.onFailed(RunesStatusCode.AUTH_EXPIRED);
                    }
                } else {
                    initRunesManagerCallback.onFailed(RunesStatusCode.getStatus(entityBean.getCode()));
                }
            }

            @Override
            public void onError(Response<String> response) {
                super.onError(response);
                LogUtils.debug("onError");
            }
        });
    }


    // 设置加速速度（速度范围为1-10的正整数）
    public void setRunesSpeed(float rate, RunesStatusCallback runesStatusCallback) {
        if (!isInitRunesManager) return;
        try {
            triggerRunes();
            // 调用jni方法进行加速
            if (rate < 1) {
                Tool.update(1);
                return;
            }
            if (rate > 10) {
                Tool.update(10);
                return;
            }
            Tool.update(rate);
            runesStatusCallback.onSuccess();
        } catch (TriggerRunesException e) {
            e.printStackTrace();
            runesStatusCallback.onFailed(RunesStatusCode.getStatus(e.getCode()));
        }
    }

    private void triggerRunes() throws TriggerRunesException {
        if (!isInitRunes) {
            int code = Tool.init(mContent, Base64.getDecoder().decode(token), Base64.getDecoder().decode(token).length);
            if (code == RunesStatusCode.AVAILABLE.getCode()) {
                isInitRunes = true;
            } else {
                throw new TriggerRunesException(code);
            }
        }
    }


    /**
     * 添加加速球View
     *
     * @param mContext
     */
    public void showFloatBallView(final Activity mContext, InitRunesManagerCallback initRunesManagerCallback) {
        String configData = (String) SharedPreferenceUtils.getData(preferences, Common.SPEED_CONFIG_FILE, "");
        DataBean dataBean = new Gson().fromJson(configData, DataBean.class);

        ViewManager.getInstance().init(mContext, new MagnetViewListener() {
            @Override
            public void onRemove(RunesFloatBall magnetView) {

            }

            @Override
            public void onClick(RunesFloatBall magnetView) {
                float rateParams;
                if (isSpeeding) {
                    isSpeeding = false;
                    magnetView.setStart();
                    rateParams = 1;
                } else {
                    isSpeeding = true;
                    magnetView.setPause();
                    rateParams = dataBean.getRatio() * rateFloat;
                }
                // 设置加速
                setRunesSpeed(rateParams, new RunesStatusCallback() {
                    @Override
                    public void onSuccess() {
                        initRunesManagerCallback.onSuccess();
                    }

                    @Override
                    public void onFailed(RunesStatusCode runesStatusCode) {
                        initRunesManagerCallback.onFailed(runesStatusCode);

                        // 清空配置文件
                        SharedPreferenceUtils.putData(preferences, Common.SPEED_CONFIG_FILE, "");
                    }
                });
            }

            @Override
            public void onLongClick(RunesFloatBall magnetView) {
                LogUtils.debug("FloatingMagnetView----------------onLongClick");

                showRunesDialog(mContext, magnetView, dataBean, new RunesStatusCallback() {
                    @Override
                    public void onSuccess() {
                        if (initRunesManagerCallback != null) {
                            initRunesManagerCallback.onSuccess();
                        }
                    }

                    @Override
                    public void onFailed(RunesStatusCode runesStatusCode) {
                        // 清空配置文件
                        SharedPreferenceUtils.putData(preferences, Common.SPEED_CONFIG_FILE, "");
                        if (initRunesManagerCallback != null) {
                            initRunesManagerCallback.onFailed(runesStatusCode);
                        }
                    }
                });
            }

            @Override
            public void onActionDown(RunesFloatBall magnetView) {
                ViewManager.getInstance().hideGuideTwoImageView();
            }

            @Override
            public void onActionMove(RunesFloatBall magnetView) {
                ViewManager.getInstance().showRemoveBallView();
            }

            @Override
            public void onActionUp(RunesFloatBall magnetView) {
                //todo 需要重写隐藏悬浮球的方案
                Rect floatRect = new Rect();
                magnetView.getGlobalVisibleRect(floatRect);

                Rect removeBallViewRect = new Rect();
                ViewManager.getInstance().getRemoveBallView().getGlobalVisibleRect(removeBallViewRect);

                float ratio = ViewUtil.getRatio(floatRect, removeBallViewRect);
                if (ratio > 0.25) { // 相交的地方大于0.25 就隐藏
                    magnetView.hide();
                }

                ViewManager.getInstance().hideRemoveBallView();
            }
        });

        boolean isShowGuideDialog = (boolean) SharedPreferenceUtils.getData(preferences, Common.IS_SHOW_GUI_DIALOG, true);
        if (isShowGuideDialog) showGuideDialog(mContext);
    }

    /**
     * 展示引导dialog
     *
     * @param mContext
     */
    private void showGuideDialog(Context mContext) {
        RunesGuideDialog customDialog = new RunesGuideDialog(mContext, new int[]{
                R.id.iv_alphaspeed_notification_button,
                R.id.tv_alphaspeed_know
        });
        customDialog.setOnDialogItemClickListener((dialog, view) -> {
            int id = view.getId(); //
            if (id == R.id.iv_alphaspeed_notification_button) {
                isShowGuideDialog = !isShowGuideDialog;
                if (isShowGuideDialog) {
                    ((ImageView) view).setImageResource(R.drawable.alphaspeed_ring_blue);
                } else {
                    ((ImageView) view).setImageResource(R.drawable.alphaspeed_ring_blue_selected);
                }

            } else if (id == R.id.tv_alphaspeed_know) {
                SharedPreferenceUtils.putData(preferences, Common.IS_SHOW_GUI_DIALOG, isShowGuideDialog);
                customDialog.dismiss();
            }
        });
        customDialog.show();
    }

    // 展示加速弹窗dialog
    public void showRunesDialog(Activity context, RunesFloatBall magnetView, DataBean dataBean, RunesStatusCallback runesStatusCallback) {
        if (!isInitRunesManager) return;
        try {
            triggerRunes();
            // 开启加速弹窗
            RunesDialog customDialog = new RunesDialog(context, new int[]{
                    R.id.alphaspeed_switch_button,
                    R.id.alphaspeed_switch_close,
                    R.id.alphaspeed_play,
                    R.id.alphaspeed_sub,
                    R.id.alphaspeed_add,
            }, isSpeeding);
            customDialog.setOnDialogItemClickListener((dialog, view) -> {
                int id = view.getId(); //
                if (id == R.id.alphaspeed_switch_close) {
                    customDialog.dismiss();
                } else if (id == R.id.alphaspeed_switch_button) {
                    if (isShowSpeedBall) {
                        isShowSpeedBall = false;
                        magnetView.hide();
                        ((ImageView) view).setImageResource(R.drawable.alphaspeed_switch_close);
                    } else {
                        isShowSpeedBall = true;
                        magnetView.show();
                        ((ImageView) view).setImageResource(R.drawable.alphaspeed_switch_open);
                    }
                } else if (id == R.id.alphaspeed_play) {
                    if (isSpeeding) {
                        isSpeeding = false;
                        magnetView.setStart();
                        ((ImageView) view).setImageResource(R.drawable.alphaspeed_play);
                    } else {
                        isSpeeding = true;
                        magnetView.setPause();
                        ((ImageView) view).setImageResource(R.drawable.alphaspeed_onpause);
                    }
                } else if (id == R.id.alphaspeed_sub) {
                    customDialog.setSubSpeed();

                    SharedPreferenceUtils.putData(preferences, Common.CURRENT_SPEED_COUNT, customDialog.getCurrentSpeed());


                    setRunesSpeed(customDialog.getCurrentSpeed() * dataBean.getRatio(), new RunesStatusCallback() {
                        @Override
                        public void onSuccess() {
                            runesStatusCallback.onSuccess();
                        }

                        @Override
                        public void onFailed(RunesStatusCode runesStatusCode) {
                            runesStatusCallback.onFailed(RunesStatusCode.getStatus(runesStatusCode.getCode()));
                        }
                    });
                } else if (id == R.id.alphaspeed_add) {
                    customDialog.setAddSpeed();

                    SharedPreferenceUtils.putData(preferences, Common.CURRENT_SPEED_COUNT, customDialog.getCurrentSpeed());

                    setRunesSpeed(customDialog.getCurrentSpeed() * dataBean.getRatio(), new RunesStatusCallback() {
                        @Override
                        public void onSuccess() {
                            runesStatusCallback.onSuccess();
                        }

                        @Override
                        public void onFailed(RunesStatusCode runesStatusCode) {
                            runesStatusCallback.onFailed(RunesStatusCode.getStatus(runesStatusCode.getCode()));
                        }
                    });
                }
            });

            customDialog.show();
        } catch (TriggerRunesException e) {
            e.printStackTrace();
            runesStatusCallback.onFailed(RunesStatusCode.getStatus(e.getCode()));
        }
    }
}
